import { defineStore } from "pinia";
import { getAdcode, getWeatherByAdcode,getAdcodeByCityName } from '@/api/index'
import { ref } from "vue";


export const useWeatherStore = defineStore("weather", () => {
    const adCode = ref()
    const livesWeather = ref([])//weather表示头部实时天气的信息
    const cityName = ref('')//搜索城市名称
    const forecast=ref([]);//存放天气预报
    const options1=ref({});//
    const options2=ref({});
    const forecastArr=ref([]);
    const forecastArr1=ref([]);//用于存放信息页面的天气预报信息
    const citys = ref([])//存放内存citys的adcode数组
    const renderCitys=ref([])
    const week = ref(['周一', '周二', '周三', '周四', '周五', '周六', '周日'])
//获取adcode方法
const getCode = async function (ip) {
  const { data } = await getAdcode(ip)
  adCode.value = data.adcode
  return adCode.value
}

//获取当天头部天气方法
const getWeather = async function (ip) {
    const res=await getCode(ip)
    const {data} = await getWeatherByAdcode(res,'base')
    // console.log(data)
    // console.log(data.forecasts)
    livesWeather.value=data
    return livesWeather.value
}

//通过城市名获取adcode
const getCodeByCityName = async function (cityName) {
    const {data}= await getAdcodeByCityName(cityName)
    // console.log(data,"data")
    if(data.status===1){
        adCode.value = data.geocodes[0].adcode
        console.log(adCode.value,"adcode")
        return adCode.value
    }
    else{
        return data
    } 
}

//获取天气预报的天气
const getForecasts =async function (cityname){
    //先根据城市名获取到adcode
    let res=await getCodeByCityName(cityname)
    // console.log(res,"res")
    //当staus为1时，获取到adcode
    if(res.status==1){
      const  adcode=res.geocodes[0].adcode
    //   console.log(adcode,"adcode")
    // 根据adcode获取天气预报
    let {data}=await getWeatherByAdcode(adcode)
    // console.log({data},"res1")
    // console.log(data.forecasts,"forecasts")
    return data
    }
   //当status为0时，获取不到adcode
   else{
    return res
   }
    // console.log(geocodes[0],"res")
    //  geocodes=geocodes[0].adcode
}
//searchCity 搜索城市
const searchCity=async(name)=>{
    const res=  await getForecasts(name)
    if(res.status==1){
        // console.log(res,"res")
        // console.log(res.forecasts[0].city,"city")
        return res.forecasts[0].city
    }
    else{
        return res
    }
}
const getForecastArr=()=>{
    forecastArr.value = forecast.value.map((item,index )=>{
        if(index==0){
           return{
               day:"今天",
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
        }
       else if(index==1){
           return{
               day:"明天",
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
       }
       else{
           return{
               day:week.value[item.week-1],
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
        }
     })

     return forecastArr
}

//渲染首页图表
const renderIndexchart=async(ip)=>{
   const adcode= await getCode(ip)
   const {data} = await getWeatherByAdcode(adcode,'all')
   forecast.value=data.forecasts[0].casts
//    console.log(forecast.value,"data")
    getForecastArr()
    options1.value={
        xAxis:{
            type:"category",
            show:false,
            // boundaryGap:false,
            
        },
        yAxis:{
            type:"value",
            show:false,
        },
        grid:{
            left:0,
            right:0,
            bottom:0,
            top:"5%",
        },
        series:[
            {
                
                type:"line",
                name:"白天气温",
                
                data:forecastArr.value.map(item=>item.daytemp),
                label:{
                    show:true,
                    top:"5%",
                    fontSize:10,
                    color:"#fff",
                    formatter:function(params){
                        return "白"+ params.value+"°C"
                    }
                },
            },
            {
                type:"line",
                name:"夜间气温",
                data:forecastArr.value.map(item=>item.nighttemp),
                label:{
                    show:true,
                    top:"5%",
                    fontSize:10,
                    color:"#fff",
                    formatter:function(params){
                        return "晚"+ params.value+"°C"
                    },
                    offset:[0,30]
                },
            },
        ]

    }
}


//渲染详情页面（第二个页面）
const renderchart1=async(name)=>{
const forecastArr= await getForecastArr1(name)
//   console.log(forecastArr,"arr")
    options2.value={
        xAxis:{
            type:"category",
            show:false,
            // boundaryGap:false,
            
        },
        yAxis:{
            type:"value",
            show:false,
        },
        grid:{
            left:0,
            right:0,
            bottom:0,
            top:"15%",
        },
        series:[
            {
                
                type:"line",
                name:"白天气温",
                
                data:forecastArr.map(item=>item.daytemp),
                label:{
                    show:true,
                    top:"5%",
                    fontSize:10,
                    color:"#fff",
                    formatter:function(params){
                        return "白"+ params.value+"°C"
                    }
                },
            },
            {
                type:"line",
                name:"夜间气温",
                data:forecastArr.map(item=>item.nighttemp),
                label:{
                    show:true,
                    top:"5%",
                    fontSize:10,
                    color:"#fff",
                    formatter:function(params){
                        return "晚"+ params.value+"°C"
                    },
                    offset:[0,30]
                },
            },
        ]

    }
    // console.log(options2,"options2")
}
//查看城市具体信息
const getInfoCity=async (name)=>{
    // console.log(name)
    const {forecasts}=await getForecasts(name)
    // console.log(forecasts,"res")
    forecast.value=[],
    forecastArr.value=[]
    forecast.value=forecasts[0].casts
    getForecastArr()
    return forecastArr
}
//获取详情页预报
const getForecastArr1=async (code)=>{
    const forecast=await getWeatherByAdcode(code, 'all')
    forecast.value=forecast.data.forecasts[0].casts
    // console.log(forecast.value,"res")
    forecastArr1.value = forecast.value.map((item,index )=>{
        if(index==0){
           return{
               day:"今天",
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
        }
       else if(index==1){
           return{
               day:"明天",
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
       }
       else{
           return{
               day:week.value[item.week-1],
               date:item.date.slice(5),
               dayweather:item.dayweather,
               daypower:item.daypower,
               daytemp:item.daytemp,
               nighttemp:item.nighttemp,
           }
        }
     })
    return forecastArr1.value
}
//获得城市列表(内存里的)
const getCity=()=>{
    const cityList=  JSON.parse(localStorage.getItem('cityList')||'[]')
    // console.log(cityList)
    citys.value=cityList
}
const AddCity=async (code)=>{
    getCity()
    const weather = ref([]) //存放当天天气信息
    //获取当天天气情况
  const { data } = await getWeatherByAdcode(code, 'base')
  weather.value = data.lives[0].adcode
  console.log(weather.value,"weather")
  
 citys.value.push(weather.value)
// console.log(citys.value,"citys")
return citys.value
}
//渲染页面函数
const render=async()=>{
getCity()
const newArr=citys.value.map(async item=>{
 return  await getWeatherByAdcode(item,"base")
})
const fn= Promise.all(newArr).then(res=>{
    // renderCitys.value=res
    return res
})
const res= await fn
// console.log(res,"res")
renderCitys.value=res.map(item=>{
   return  item.data.lives.map(item=>{
    return {
      city:item.city,
      temperature:item.temperature
    }
 }
)

})
return renderCitys.value;
}

return {
    renderCitys,
    citys,
    options2,
    forecastArr1,
    forecastArr,
    adCode,
    livesWeather,
    forecast,
    options1,
    cityName,
    getCode,
    getWeather,
    getCodeByCityName,
    getForecasts,
    searchCity,
    renderIndexchart,
    getForecastArr,
    getInfoCity,
    getForecastArr1,
    renderchart1,
    getCity,
    AddCity,
    render
}
});
